<template>
  <!-- start 计划任务进度 -->
  <div class="plan-task-info-record">
    
    <!-- start 时间轴 -->
    <div class="plan-task-timeline" :style="inputState?'padding-bottom:210px;':'padding-bottom:70px;'" ref="timeline">
      <base-timeline 
        :data="recordPage.list" 
        :record-render="renderRecord" 
        :loading="recordLoading"
        :loadmore="recordPage.hasNextPage"
        @load="loadmore"
      />
    </div>
    <!-- end 时间轴 -->
  </div>
  <!-- end 计划任务进度 -->
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
/* utils */
import { isOpenData } from '@src/util/platform';
import Page from '@model/Page';
import { formatDate } from 'pub-bbx-utils'
import { translateAction } from 'src/util/record'
/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
/* image */
import { isBasicEditionHideEvent } from '@shb-lib/version';
/* mixin */
import { ConnectorModuleConnectorRecordMixin } from '@src/modules/connector'

export default {
  name: 'task-plan-info-record',
  inject: ['initData'],
  mixins: [ConnectorModuleConnectorRecordMixin],
  props: {
    showTemplate: {
      type: Boolean,
      default: true
    },
    shareData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      params: {
        planId: this.planTaskId,
        pageNum: 1,
        pageSize: 15,
      },
      recordLoading: false,
      recordPage: new Page(),
      inputState:false
    }
  },
  computed: {
    // 权限
    authorities(){
      let user = this.loginUser || {};
      return user.authorities || {};
    },
    allTaskEdit() {
      return this.authorities['TASK_EDIT'] === 3;
    },
    /** 是否允许操作 */
    allowOperate(){
      return this.task?.isDelete === 0;
    },
    /** 查看单权限 */
    allowTaskView() {
      return this.initData?.canViewTask === true;
    },
    loginUser(){
      return this.initData?.loginUser || {};
    },
    task() {
      return this.shareData?.task || {};
    },
    planTaskId() {
      return this.task.id
    },
    taskNo() {
      return this.task?.taskNo;
    },
    // 基础版功能隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent() 
    },
  },
  watch: {
    planTaskId: {
      handler(newValue) {
        if(newValue) {
          this.initializeRecord()
        }
      }
    }
  },
  mounted() {
    this.initializeRecord();
    this.$eventBus.$on(TaskEventNameMappingEnum.UpdatePlanTaskRecord, this.searchRecord);
  },
  beforeDestroy() {
    this.$eventBus.$off(TaskEventNameMappingEnum.UpdatePlanTaskRecord, this.searchRecord);
  },
  methods: {
    getTime(time) {
      try {
        return formatDate(time)
      } catch (error) {
        console.warn('task-plan-info-record : getTime -> error', error)
        return ''
      }
    },
    // 普通字符串转成数组
    renderStringChangeArray(string){
      let arrayStr = string ?? ''
      let arr = []
      if(arrayStr.length){
        arrayStr = arrayStr.substring(1, arrayStr.length - 1).split(',')
        arrayStr.forEach(item => {
          item = item.substring(1, item.length - 1)
          arr.push(item)
        }) 
      }
      return arr
    },
    /** 
     * 同时满足以下条件允许删除该记录
     * 1. 该记录没有被删除
     * 2. 工单编辑权限（CUSTOMER_EDIT）值为3 或者 是创建人
     * 3. 该工单没有被删除
     */
    allowDeleteRecord(item){
      let isDelete = item.content.isDelete == 'true'
      let user = this.loginUser
      let isCreator = item.userId == user.userId

      return !isDelete && (this.allTaskEdit || isCreator) && this.allowOperate;
    },
    /** 
     * @description 抓取信息动态
    */
    fetchRecord(params){
      params.planId = this.planTaskId
      return TaskApi.getPlanTaskRecord(params).then(data => {
        let list = data?.result?.list || []
        list.forEach(record => {
          try {
            // record.attachments = JSON.parse(record.attachments);
            // record.content = JSON.parse(record.content);
          } catch (error) {
            record.content = { updateContent: record.content };
            console.warn('searchRecord recordPage.list.forEach -> error', error)
          }
        })
        return data;
      })
    },
    /** 
     * @description 初始化信息动态
    */
    async initializeRecord() {
      this.params.pageNum = 1;
      this.searchRecord();
    },
    /** 
     * @description 加载下一页
    */
    async loadmore() {
      try {
        this.params.pageNum++;
        this.recordLoading = true;
        
        let data = await this.fetchRecord(this.params);
        
        this.recordLoading = false
        this.recordPage.merge(data.result)
        
      } catch (error) {
        this.recordLoading = false
        console.warn('loadmore -> error', error)
      }
    },

    /* 渲染基础的工单动作 */
    renderBaseTaskAction({ action, executorName, planNumber, staffId, content = {}, executorId }) {
      const overRecordsArr = this.renderStringChangeArray(content?.overRecords);
      return (<i18n path="common.record.task.planTaskNormal" tag="h5">
        <span place="operator">{this.renderUserName(executorName, staffId, executorId)}</span>
        <span place="action">{ translateAction(action) }</span>
        <span place="taskno">{planNumber}</span>
        <div place="other" style={{ display: overRecordsArr.length ? 'block' : 'none' }} >{overRecordsArr[0]}</div>
      </i18n>)
    },
    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, record) {
      let { action } = record;

      if(action == '创建') return this.renderTaskCreateDom(record)
      if(action == '取消') return this.renderTaskCancelDom(record)
      if(action == '编辑') return this.renderTaskEditDom(record)
      if(action == '工单立即创建') return this.renderTaskCreateNowDom(record) // 立刻创建
      if(action == '工单调整时间') return this.renderTaskChangeTimeDom(record) // 调整时间
      if(action == '工单删除') return this.renderTaskDeleteTaskDom(record) // 删除工单
    
    },
    renderTaskCreateNowDom(record = {}) {
      let { executorName, executorId, staffId, content } = record;
      let { taskNo } = content;
      return (<i18n path="common.record.task.planTaskCreateNowDom" tag="div">
        <span place="operator">{this.renderUserName(executorName, staffId, executorId)}</span>
        <span place="taskno">{ taskNo }</span>
      </i18n>)
    },
    renderTaskChangeTimeDom(record = {}) {
      let { executorName, executorId, staffId, content } = record;
      let { newCreateTime, originCreateTime } = content
      return (<i18n path="common.record.task.planTaskChangeTimeDom" tag="div">
        <span place="operator">{this.renderUserName(executorName, staffId, executorId)}</span>
        <span place="before">{ this.getTime(originCreateTime) }</span>
        <span place="after">{ this.getTime(newCreateTime) }</span>
      </i18n>)
    },
    renderTaskDeleteTaskDom(record = {}) {
      let { executorName, executorId, staffId, content } = record;
      let { originCreateTime } = content
      return (<i18n path="common.record.task.planTaskDeleteTaskDom" tag="div">
        <span place="operator">{this.renderUserName(executorName, staffId, executorId)}</span>
        <span place="time">{ this.getTime(originCreateTime) }</span>
      </i18n>)
    },
    renderTaskCreateDom(record = {}) {
      return [
        this.renderBaseTaskAction(record)
      ]
    },
    renderTaskCancelDom(record = {}) {
      return [
        this.renderBaseTaskAction(record)
      ]
    },
    renderTaskEditDom(record = {}) {
      return [
        this.renderBaseTaskAction(record)
      ]
    },
    renderUserName(userName, staffId, userId){
      if(userId){
        if(isOpenData && staffId && userName != '自动审批') return <strong class="user-card-triggle" v-user={userId}>{<open-data type="userName" openid={staffId}></open-data>}</strong>
        return <strong class="user-card-triggle" v-user={userId}>{userName}</strong>
      }
      if(isOpenData && staffId && userName != '自动审批') return <strong>{<open-data type="userName" openid={staffId}></open-data>}</strong>
      return <strong>{userName == '自动审批' ? this.$t('common.base.autoApproveIt') : userName}</strong>
    },
    renderSynergyName(synergy, synergyStaffId){
      if(isOpenData && synergy != '自动审批' && synergyStaffId) {
        const sids = synergyStaffId.split(',') || []
        if(sids.length) return sids.map(item=><open-data key={item} type="userName" openid={item}></open-data>)
      }
      return synergy
    },
    async searchRecord() {
      try {
        this.recordLoading = true;
        
        let data = await this.fetchRecord(this.params);
        
        this.recordLoading = false;
        this.recordPage.list = [];
        this.recordPage.merge(data.result)
        
      } catch (error) {
        this.recordLoading = false;
        console.warn('searchRecord -> error', error)
      }
    }
  }
}
</script>
<style lang="scss" scope>
.plan-task-timeline{
  padding-top: 15px;
  flex: 1;
  padding-right: 15px;
  .private {
    @include fontColor();
  }
}
.plan-task-info-record {
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  background-color: #fff;
}
</style>